<?php 
namespace User\Controller;
use Think\Controller;
class RegController extends Controller{
	
	function _initialize() {
		//登录拦截，防止已经登录的再进入注册页面
		if($_SESSION['loginUser']){
			redirect('/user/setting.html'); //拦截到登录
			exit();
		}
	}
	
	public function index(){
		$this->display();
	}

	/**
	* 注册数据处理
	*/
	public function reg_post(){
		if(IS_POST){
			if($_POST['pass'] != $_POST['repass']){
				if(LANG_SET == 'zh-CN')
					_apiReturn(0,"两次密码不一致");
				else
					_apiReturn(0,"Entered passwords differ");
			}

			if(!$_POST['email'] || !$_POST['pass']){
				if(LANG_SET == 'zh-CN')
					_apiReturn(0,"邮箱或密码丢失");
				else
					_apiReturn(0,"Email and Password can not be null!");
			}	

			$m = D("Users");
			$result = $m->regByEmail($_POST['email'],$_POST['pass'],0);
			if($result['code'] < 0 && $result['code'] != -1){
				_apiReturn(0,$result['msg-'.LANG_SET]);
			}
			$_SESSION['tmpUser'] = $result['user']; //赋值给tmpUser
			//创建验证码
			if($this->_sendRegEmail($_SESSION['tmpUser']['uid'],$_SESSION['tmpUser']['username'],$_SESSION['tmpUser']['email'])){
				_apiReturn(1,'success','','/user/reg/regnext?type=email');// 跳转过去
			}else{
				_apiReturn(0,'register success ,but we can not send email to you ,system error'); //注册没问题，但是，邮件发送不出去
			}

		}
	}

	/**
	* 重新发送邮件
	*/
	public function resend_email(){
		if(!$_SESSION['tmpUser']){
			_apiReturn(0,"Please return to register page");
		}

		if(isset($_SESSION['tmpUser']['sendTime'])){
			if($_SESSION['tmpUser']['sendTime'] + 60 <= strtotime(time())){
				_apiReturn(0,'Do not repeat in 1 minute');
			}
		}
		if($this->_sendRegEmail($_SESSION['tmpUser']['uid'],$_SESSION['tmpUser']['username'],$_SESSION['tmpUser']['email'])){
			$_SESSION['tmpUser']['sendTime'] = strtotime(time());
			_apiReturn(1,'success');
		}else{
			_apiReturn(0,'sorry ,system error ,send failed');
		}	
	}

	/**
	* 发送邮件验证码
	*/
	public function _sendRegEmail($uid,$username,$email){
		$m = M('UsersInvitation');
		$map = array(
			'uid' => $uid,
			'hasuse' => 2
		);
		$codeInfo = $m->where($map)->find();
		if($codeInfo){
			$code = $codeInfo['invite_code'];
		}else{
			$code = $map['invite_code'] = get_rand_num(6);
			$map['create_time'] = $map['update_time'] = Date('Y-m-d H:i:s');
			$m->add($map); //填写进去
		}
		$tpl = F('Options/option_reg_check_tpl');
		//替换username
		$tpl = str_replace("#username#",$username,$tpl);
		//替换code
		$tpl = str_replace("#code#",$code,$tpl);
		//替换link
		$linkParam = array(
			'uid' => encrypt($uid, "checkCode"),
			'code' => encrypt($code,"checkCode")
		);
		$linkTmp = "http://".$_SERVER["HTTP_HOST"]."/user/reg/reglink/p/".$linkParam['uid']."/qc/".$linkParam['code']."/t/".base64_encode(time());
		$link = '<a href="'.$linkTmp.'" target="_blank">'.$linkTmp.'</a>';
		$tpl = str_replace("#link#",$link,$tpl);
		//将邮件发送出去
		return sendMail($email, F('Options/option_reg_check_title'), $tpl);
	}

	/**
	* 激活码验证的link
	*/
	public function reglink(){
		$result = array(
			"code" => 0,
			"msg" => "默认信息"
		);
		if(!$_GET['p'] || !$_GET['qc']){
			$result = array(
				'code'=>-1,
				'msg' => '参数缺失'
			);
		}else{
			$uid = decrypt($_GET['p'], "checkCode");
			$code = decrypt($_GET['qc'],"checkCode");
			
			$m = M('UsersInvitation');
			$map = array(
				'uid' => $uid,
				'hasuse' => 2,
				'invite_code' =>$code
			);
			
			if($m->where($map)->find()){
				//激活成功
				$data = array(
					'uid' => $uid,
					'status' => 1
				);
				$mm = D('Users');
				$mm->save($data);
				//删除掉code
				$m->where($map)->delete(); 
				//创建用户登录用的session，直接帮助用户登录

				//生成session
				/*$user = $mm->find($uid);
				unset($user['password']);
				unset($user['create_time']);
				unset($user['update_time']);
				$_SESSION['loginUser'] = $user;
				D('UserLog')->_add($user['uid'],'login','登录平台');*/ //写入日志
				//_apiReturn(1,"success","","/"); //激活成功
				$result = array(
					'code' => 1,
					'msg'  => '激活成功'
				);
			}else{
				//_apiReturn(0,"The activation code is incorrect");
				$result = array(
					'code' =>　-2,
					'msg' => '激活失败'
				);
			}
			
		}
		$this->result = $result;
		$this->display();
	}

	/**
	* 激活验证码
	*/
	public function regnext(){
		$this->display();
	}

	/**
	* 校验验证码
	*/
	public function check_code_post(){
		if(IS_POST){
			if(!$_POST['code'])
				_apiReturn(0,'Code can not be empty');
			
			if(!$_SESSION['tmpUser']){
				_apiReturn(0,'Sorry we can not get your tmp info , please click the link in the activation email to activate');
			}

			$m = M('UsersInvitation');
			$map = array(
				'uid' => $_SESSION['tmpUser']['uid'],
				'hasuse' => 2,
				'invite_code' => $_POST['code']
			);
			
			if($m->where($map)->find()){
				//激活成功
				$data = array(
					'uid' => $_SESSION['tmpUser']['uid'],
					'status' => 1
				);
				$mm = D('Users');
				$mm->save($data);
				//删除掉code
				$m->where($map)->delete(); 
				//创建用户登录用的session，直接帮助用户登录

				//生成session
				/*$user = $mm->find($_SESSION['tmpUser']['uid']);
				unset($_SESSION['tmpUser']);//及时清除这个session
				unset($user['password']);
				unset($user['create_time']);
				unset($user['update_time']);
				$_SESSION['loginUser'] = $user;
				D('UserLog')->_add($user['uid'],'login','登录平台');*/ //写入日志
				_apiReturn(1,"success","","/"); //激活成功
			}else{
				_apiReturn(0,"The activation code is incorrect");
			}
			
		}
	}
}
?>